<template>
  <div class="bg">
    <div id="login">
      <h2>拾文博客</h2>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="0">
        <el-form-item>
          <table style="width: 100%;">
            <tr>
              <el-input
                  placeholder="手机号"
                  v-model="phone"
                  class="input-with-select"
                  style="border:1px solid black;margin-top: 20px;width: 250px;"
              >
                <el-button slot="append" v-if="isSend" style="color: black">{{ timeCount }}</el-button>
                <el-button slot="append" icon="el-icon-chat-dot-square" v-else @click="sendSms"></el-button>
              </el-input>
            </tr>

            <tr>
              <el-input
                  placeholder="验证码"
                  v-model="smsCode"
                  class="input-with-select"
                  style="border:1px solid black;margin-top: 20px;width: 250px;"
              >
              </el-input>
            </tr>

            <tr>
              <td>
                <el-button type="primary" style="margin-top: 20px" round @click="submitForm('ruleForm')" class="btn">
                  登录
                </el-button>
              </td>
            </tr>
          </table>
        </el-form-item>
      </el-form>

      <!--修改用户密码-->
      <template>
        <div>
          <el-dialog
              append-to-body
              title='修改密码'
              :visible.sync="dialogVisible"
              :close-on-click-modal="false"
              :close-on-press-escape="false"
              width="40%"
              @close="closeDialog('ruleForm')">
            <el-form :model="updatePasswordRuleForm" :rules="rules" ref="ruleForm" label-width="180px"
                     class="demo-ruleForm">
              <el-form-item label="账  号" prop="username">
                <el-input v-model="updatePasswordRuleForm.username" :disabled="true" show-word-limit clearable
                          style="width: 300px;"></el-input>
              </el-form-item>

              <el-form-item label="密  码" prop="password">
                <el-input type="password" v-model="updatePasswordRuleForm.password"  clearable show-password maxlength="8" show-word-limit clearable
                          style="width: 300px;"></el-input>
              </el-form-item>

              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input type="password" v-model="updatePasswordRuleForm.confirmPassword"  clearable show-password  maxlength="8" show-word-limit clearable
                          style="width: 300px;" @input="verificationPassword"></el-input>
                <br>{{ verificationMessage }}
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="updatePassword()">提交</el-button>
                <el-button @click="closeDialog('ruleForm')">重置</el-button>
              </el-form-item>
            </el-form>
          </el-dialog>
        </div>
      </template>
    </div>

    <!--引入粒子特效-->
    <vue-particles
        color="#fff"
        :particleOpacity="0.7"
        :particlesNumber="60"
        shapeType="circle"
        :particleSize="4"
        linesColor="#fff"
        :linesWidth="1"
        :lineLinked="true"
        :lineOpacity="0.4"
        :linesDistance="150"
        :moveSpeed="2"
        :hoverEffect="true"
        hoverMode="grab"
        :clickEffect="true"
        clickMode="push"
        class="lizi"
    >
    </vue-particles>
  </div>
</template>

<script>
export default {
  data() {
    return {

      ruleForm: {
        phone: '',
        smsCode: ''

      },
      //添加设置
      phone: '18848431874',
      smsCode: '',
      sendMsg: '发送短信',
      timeCount: 60,
      isSend: false,
      intervalBtn:{}, //定时器
      rules: {
        phone: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {min: 11, max: 11, message: '长度在11 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '密码不可为空', trigger: 'blur'},
          {min: 6, max: 8, message: '长度在6-8 个字符', trigger: 'blur'}
        ],
        confirmPassword: [
          {required: true, message: '请确认密码', trigger: 'blur'},
          {min: 6, max: 8, message: '长度在6-8 个字符', trigger: 'blur'}
        ],
      },

      instructions: 1,  // 指令，判断操作的方法
      dialogVisible: false,      // 弹出框状态【修改密码】，默认隐藏
      updateData: [],
      username:'',
      verificationMessage: '',
      updatePasswordRuleForm: {
        username: '',
        password: '',
        confirmPassword: '',
      }
    };
  },
  methods: {
    submitForm() {
      let addOrSetData = this.ruleForm;

      if (this.phone === null || this.phone === undefined || this.phone === '') {
        this.$message({type: 'error', message: "电话号码不能为空"})
        return;
      }
      if (this.smsCode === null || this.smsCode === undefined || this.smsCode === '') {
        this.$message({type: 'error', message: "验证码不能为空"})
        return;
      }
      this.checkSms();
    },
    sendSms() {
      if (this.phone == null || this.phone == '') {
        this.$message({
          type: 'error',
          message: "手机号不能为空"
        })
        return;
      }
      //验证手机号格式
      // if (this.phone.substr(0, 2) != 13 && this.phone.substr(0, 2) != 18 && this.phone.substr(0, 2) != 15 && this.phone.substr(0, 2) != 18 && this.phone.substr(0, 3) != 157`` || this.phone.length != 11) {
      //   alert("手机号格式不正确");
      //   return;
      // }
      //已经发送过短信，就不允许再次发送
      if (this.isSend) {
        return;
      }
      this.axios.get("http://localhost:9090/sms/sendSmsCode?phoneNumber=" + this.phone).then(function (response) {
        if (response.data.code == 1) {
          this.$message({
            type: 'success',
            message: "短信发送成功"
          })
        } else if (response.data.code == 2) {
          this.$message({
            type: 'error',
            message: "短信发送失败，请稍后重试"
          })
        }
      })
      //改变短信发送状态和按钮状态, 60秒内不重复发送
      this.isSend = true;
      this.changeStyle();
    },
    changeStyle() {
      this.intervalBtn = setInterval(() => {
        if (this.timeCount <= 0) {
          this.isSend = false;
          // 清除定时器
          clearInterval(this.intervalBtn)
          this.sendMsg = "发送短信"
          this.timeCount = 60;
        }
        // 倒计时
        this.timeCount--
      }, 1000)
    },
    checkSms() {
      let then = this;
      this.axios.get("http://localhost:9090/sms/checkSmsCode?phoneNumber=" + this.phone + "&smsCode=" + this.smsCode)
          .then(function (response) {
            if (response.data.code == 1) {
              // 短信验证成功
              console.log("短信验证成功")
              if (then.instructions == 1) {
                console.log("短信验证成功，执行短信验证码登录")
                then.axios.get("http://localhost:9090/system/users/phoneLogin?phone=" + then.phone).then((response) => {
                  if (response.data.code === 200) {
                    let jwt = response.data.data;
                    // console.log("登录成功：获得令牌："+ jwt);
                    localStorage.setItem('jwt', jwt);
                    then.$message({
                      type: 'success',
                      message: "登录成功"
                    });
                    then.$router.push('/admin');
                  } else {
                    then.$message({
                      type: 'error',
                      message: response.data.message
                    });
                  }
                })
              } else if (then.instructions == 2) {
                console.log("短信验证成功，执行修改弹窗")
                // 信息回显
                then.axios.get("http://localhost:9090/system/users/getUserNameByPhone?phone="+then.phone).then((response) => {
                  then.updatePasswordRuleForm.username = response.data;
                  console.log("根据手机号查询到用户账号："+response.data)
                  then.dialogVisible = true;
                })
              }
            } else if (response.data.code == 2) {
              this.$message({
                type: 'error',
                message: "短信验证失败"
              })
            }
          })
    },


    /**
     * 验证密码
     */
    verificationPassword() {
      if (this.updatePasswordRuleForm.password !== this.updatePasswordRuleForm.confirmPassword) {
        this.verificationMessage = '密码不一致'
      } else {
        this.verificationMessage = '';
      }
    },

    /**
     * 修改密码
     */
    updatePassword() {
      if (this.updatePasswordRuleForm.password !== this.updatePasswordRuleForm.confirmPassword) {
        return;
      }
      this.axios.post("http://localhost:9090/system/users/updatePasswordByUserName", this.updatePasswordRuleForm).then((response) => {
        if (response.data.code === 200) {
          this.$message({
            type: 'success',
            message: "修改成功"
          });
          this.$router.push('/login');
        }
      })
    },


    /**
     * 清除弹窗数据及遗留效果
     */
    closeDialog(ruleForm) {
      if (this.$refs[ruleForm] !== undefined) {
        this.$refs[ruleForm].resetFields();
      }
    },
  },
  created() {
    let id = this.$route.query.id
    if (id !== undefined && id != null && id > 0) {
      this.instructions = id;
      console.log("获取到执行方法参考值"+id)
    }
    // this.getVerificationCode();
  }
}
</script>


<style scoped>
.bg {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: url('https://ts1.cn.mm.bing.net/th/id/R-C.51676491f69a1c1b3b043035c7565760?rik=ahRHaUMH3E02lg&riu=http%3a%2f%2fwww.kuaipng.com%2fUploads%2fpic%2fb%2f2019%2f09-13%2f69781%2fbeijing_pic_69781_1200_600.jpg&ehk=F9XpXpcQR%2f3zuIkcEWrvMl8myfV4bm%2fwfw4lDwMbVy8%3d&risl=&pid=ImgRaw&r=0');
  background-size: 100% 100%;
}

body {
  -moz-user-select: none;
}

#login {
  height: 320px;
  width: 350px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.25);
  background: #ffffff;
  opacity: 0.85;
  position: absolute;
  top: 20%;
  left: 40%;
  text-align: center;
  display: flex;
  flex-direction: column; /*横向*/
  padding: 30px;
  border-radius: 15px;
}

#login h2 {
  padding-bottom: 30px;
}

.btn {
  width: 80%;
  margin: auto;
}

.reg {
  float: right;
  height: 10px;
  line-height: 20px;
  position: relative;
  top: -10px;
}

a {
  color: #908f8f;
  text-decoration: none;
}
</style>

